package org.jaaksi.androidforflutterdemo.server;

import libcore.config.LibConfig;
import libcore.net.upload.ProgressListener;
import libcore.net.core.BaseRetrofitCreator;
import libcore.net.interceptor.UploadInterceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

public class ApiClient {
  private static Retrofit sRetrofit;

  static {
    sRetrofit = new BaseRetrofitCreator() {
      @Override
      public OkHttpClient getHttpClient() {
        return new OkHttpCreator().create();
      }

      @Override
      public String getBaseUri() {
        return LibConfig.getBaseUrl();
      }
    }.create();
  }

  /**
   * 创建api Service
   */
  public static <S> S create(Class<S> serviceClass) {
    return sRetrofit.create(serviceClass);
  }

  public static <S> S create(Class<S> serviceClass, ProgressListener progressListener) {
    final UploadInterceptor interceptor = new UploadInterceptor(progressListener);
    Retrofit retrofit = new BaseRetrofitCreator() {
      @Override
      public OkHttpClient getHttpClient() {
        return new OkHttpCreator() {
          @Override
          public OkHttpClient.Builder customize(OkHttpClient.Builder builder) {
            return super.customize(builder).addNetworkInterceptor(interceptor);
          }
        }.create();
      }

      @Override
      public String getBaseUri() {
        return LibConfig.getBaseUrl();
      }
    }.create();
    return retrofit.create(serviceClass);
  }
}
